<?php

class UpperController extends Controller
{
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','delete','doit'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Upper;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Upper']))
		{
			$model->attributes=$_POST['Upper'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->upper_id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Upper']))
		{
			$model->attributes=$_POST['Upper'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->upper_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete()
	{
		$upperId = NC::_p('cn','');
		$upperId = (int)substr($upperId,2);
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			if(Upper::model()->deleteAll('user_id=:user_id and upper_user_id=:upper_user_id',array(':user_id'=>Yii::app()->user->id,':upper_user_id'=>$upperId))){
				NC::json(true);
			}
			NC::json(false,'请求错误，请您重试');
		}
		else
			NC::json(false,'请求错误，请您重试');
		throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		//判断用户情况，先逻辑判断，以后改成CBAC系统判断
		$userId = (int)NC::_g('id',0);
		$isSelf = false;
		if(!$userId){
			if(Yii::app()->user->isGuest)
				Yii::app()->user->loginRequired();
			else{
				$userId = Yii::app()->user->id;
				$isSelf = true;
			}
		}else{
			if(!Yii::app()->user->isGuest && Yii::app()->user->id == $userId)$isSelf = true;
		}//end
		if($isSelf){
			$user = Upper::getUpper($userId,'self');
			$this->render('index',array('upper'=>$user));
		}else{
			$dataProvider = new CActiveDataProvider('News',array(
				'criteria'=>array(
					'order'=>'post_time DESC',
					'condition'=>'user_id='.$userId,
				),
				'pagination'=>array(
					'pageSize'=>10,
				),
			));
			//用户信息
			$user = User::model()->findByPk($userId);
			//用户的粉丝
			$fans = Fans::model()->findAll("user_id=$userId AND is_outdate = 'no' order by fans_time DESC LIMIT 12");
			if(!Yii::app()->user->isGuest){
				$upper = Upper::model()->find("user_id=". Yii::app()->user->id . " and upper_user_id=$userId and type='user'");
			}else $upper = false;
			$isUpper = $upper ? true : false;//true为是上游
			$this->render('otherindex',array('dataProvider'=>$dataProvider,'user'=>$user,'fans'=>$fans,'isUpper'=>$isUpper));
		}
		/*
			$dataProvider=new CActiveDataProvider('Upper');
			
			$this->render('otherindex',array(
				'dataProvider'=>$dataProvider,
			));
		*/
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Upper('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Upper']))
			$model->attributes=$_GET['Upper'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Upper::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='upper-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	public function actionDoit(){
		if(Yii::app()->request->isPostRequest)
		{
			$upper_user_id = NC::_p('do','');
			$type = (string)substr($upper_user_id,0,2);
			$upper_user_id = (int)substr($upper_user_id,2);
			switch($type){
				case 'de'://delete uppper
					$r = Upper::delUPper($upper_user_id);
					if(is_array($r)){
						Yii::log($r,'error');
						NC::json(false,'服务错误，请重试！');
					}else
						NC::json(true,'de');
				break;
				case 'ad'://fixed upper
				//NC::json(false,"fds");
					if(Upper::addUpper($upper_user_id))
						Nc::json(true,'ad');
				break;
				default:
					NC::json(false,'无效的请求，请您重试！');
			}
			NC::json(false,'请求错误，请您重试');
		}
		else
			NC::json(false,'请求错误，请您重试');
		throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
}
